package cn.exrick.xboot.modules.masterdata.server.servers;

import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.utils.jiuqi.utils.EncryptUtil;
import cn.exrick.xboot.modules.base.entity.Role;
import cn.exrick.xboot.modules.base.entity.User;
import cn.exrick.xboot.modules.base.entity.UserRole;
import cn.exrick.xboot.modules.base.service.RoleService;
import cn.exrick.xboot.modules.base.service.UserService;
import cn.exrick.xboot.modules.base.service.mybatis.IUserRoleService;
import cn.exrick.xboot.modules.base.serviceimpl.UserServiceImpl;
import cn.exrick.xboot.modules.masterdata.entity.MasterUser;
import cn.exrick.xboot.modules.masterdata.entity.dto.MasterUserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class MasterUserService {
    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private IUserRoleService iUserRoleService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     *MasterUserDto--》User持久化
     * @param masterUserDto
     * @return
     */
    public MasterUserDto saveUser(MasterUserDto masterUserDto){
        List<MasterUser> masterUserList = masterUserDto.getMasterUserList();
        List<MasterUser> sucMasterUserList = new ArrayList<>();
        for (MasterUser masterUser : masterUserList) {
            try{
            User user = null;
            //先通过username查询用户
            User byUsername = userServiceImpl.myfindByUsername(masterUser.getIdcard());//masterUser.getIdcard()
            if (CommonConstant.MASTER_FLAG.equals(masterUser.getFlag())) {//数据的删除状态判断
                //进行数据的删除操作
                if (byUsername != null) {
                    //删除指的是将该用户禁用（停用）
                    BeanUtils.copyProperties(masterUser, byUsername);
                    byUsername.setStatus(CommonConstant.USER_STATUS_LOCK);
                    User save = userService.update(byUsername);
                    //手动更新缓存
                    redisTemplate.delete("user::"+save.getUsername());
                }else{
                    log.info("当前用户不存在portal系统中无法停用："+masterUser.getIdcard());
                    user = new User();
                    //进行字段值的初始化(账号，密码，邮箱，加密身份证号，时间,角色，TODO 组织结构)
                    BeanUtils.copyProperties(masterUser, user);
                    user = initUser(user);
                    user.setStatus(CommonConstant.USER_STATUS_LOCK);
                    //持久化user对象
                    User save = userService.save(user);
                    //User save= userService.update(user);
                    //为init角色(所有用户初始化为普通用户 Role.name=ROLE_USER)
                    List<Role> role_user = roleService.findByName("ROLE_USER");
                    if (role_user.size() > 0) {
                        Role role = role_user.get(0);
                        UserRole ur = new UserRole();
                        ur.setUserId(save.getId());
                        ur.setRoleId(role.getId());
                        iUserRoleService.save(ur);
                    }

                }
            }else {
                if (byUsername != null) {
                    byUsername.setStatus(CommonConstant.USER_STATUS_NORMAL);
                    BeanUtils.copyProperties(masterUser, byUsername);
                    User save = userService.update(byUsername);
                    redisTemplate.delete("user::"+save.getUsername());
                } else {
                    user = new User();
                    //进行字段值的初始化(账号，密码，邮箱，加密身份证号，时间,角色，TODO 组织结构)
                    BeanUtils.copyProperties(masterUser, user);
                    user = initUser(user);

                    //持久化user对象
                    User save = userService.save(user);
                    //User save= userService.update(user);
                    //为init角色(所有用户初始化为普通用户 Role.name=ROLE_USER)
                    List<Role> role_user = roleService.findByName("ROLE_USER");
                    if (role_user.size() > 0) {
                        Role role = role_user.get(0);
                        UserRole ur = new UserRole();
                        ur.setUserId(save.getId());
                        ur.setRoleId(role.getId());
                        iUserRoleService.save(ur);
                    }
                }
            }
            }catch (Exception e){
                log.error("同步主数据"+masterUser.getIdcard()+"出错");
                e.printStackTrace();
                continue;
            }
            sucMasterUserList.add(masterUser);
        }
            masterUserDto.setMasterUserList(sucMasterUserList);
            return masterUserDto;

    }

    /**
     * 字段值的初始化(账号，密码，邮箱，加密身份证号，时间 ,TODO 组织结构)
     */
    public User initUser(User user){
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        //1.init密码(规则：以身份证号后8位作为初始化的密码)
        String idcard = user.getIdcard();
        String newPass="123456";
        if(idcard.length()-8>0){
            newPass = idcard.substring(idcard.length() - 8, idcard.length());
        }
        String newEncryptPass= new BCryptPasswordEncoder().encode(newPass);
        user.setPassword(newEncryptPass);
        //2.init邮箱
        String email="employee@163.com";
        user.setEmail(email);
        //3.init账号
        user.setUsername(user.getIdcard());
        //4.init加密身份证号
        String idcardEncryption = null;
        try {
            idcardEncryption = EncryptUtil.DESencode(idcard, CommonConstant.ENCRYPT_KEY );
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("加密后的身份证号："+idcardEncryption);
        user.setIdcardEncryption(idcardEncryption);
        //TODO 初始化组织结构(因为目前在主数据获取不到关于组织结构的数据，所以在这先将默认的值设置到账户信息中)
        user.setDepartmentId("40322777781112832");
        return user;
    }
}
